<template>
  <div class="yzh-basic">
    <div class="flex justify-between pb-3 items-center">
      <TitleName
        title="发票记录"
        icon="i-carbon-bookmark-filled"
        class="title"
      ></TitleName>
      <el-row class="w-6/12 items-center" :gutter="20" justify="space-between">
        <el-col :span="14">
          <span v-if="queryParams.orderId">
            已开票金额：<span class="text-blue-500"
              >¥{{ countCrudData.invoicedPrice }}</span
            >
            未开票金额：<span class="text-blue-500"
              >¥{{ countCrudData.unInvoicePrice }}</span
            ></span
          ></el-col
        >
        <el-col :span="5" v-if="props.tableParam.type !== 'project'">
          <el-button
            class="w-full"
            type="primary"
            @click="handleAdd"
            v-hasPermi="['financial:invoiceManage:add']"
          >
            添加</el-button
          ></el-col
        ><el-col :span="5">
          <!--  icon="Download" -->
          <el-button class="w-full" type="primary" plain @click="handleExport"
            >导出</el-button
          >
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="loading"
      :data="tableList"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column prop="invoiceDate" label="开票日期">
        <template #default="scope">
          <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="开票金额(元)"> </el-table-column>
      <el-table-column prop="type" label="发票类型">
        <template #default="scope">
          <dict-drop :options="invoice_manage_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column prop="handleUserName" label="发票经手人">
      </el-table-column>
      <el-table-column prop="invoiceRemark" label="发票备注" />
      <el-table-column prop="createTime" label="录入时间"> </el-table-column>
      <el-table-column
        prop="orderTitle"
        label="订单标题"
        v-if="queryParams.customerId"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleDetails(scope.row)"
            v-hasPermi="['financial:invoiceManage:operate']"
            >详情</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['financial:invoiceManage:operate']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            v-if="scope.row.pdfUrl"
            @click="downLoadFile(scope.row.pdfUrl)"
            >下载</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加发票 -->
    <el-dialog
      v-if="dialogOpton.open"
      :title="dialogOpton.title"
      v-model="dialogOpton.open"
      width="80%"
      :close-on-click-modal="false"
    >
      <InvoiceForm
        v-show="dialogOpton.title == '添加发票'"
        ref="invoiceForm"
        :isDialog="true"
        :invoiceData="invoiceData"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogOpton.open = false">取 消</el-button>
          <el-button type="primary" @click="handleStopSubmit">保存</el-button>
        </span></template
      >
    </el-dialog>
  </div>
</template>
<script setup name="InvoiceRecord">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import {
  listInvoice,
  getInvoiceCount,
  delInvoice
} from '@/api/invoiceManage/invoice'
import { getCustomerEditInfo } from '@/api/customerManage/customerList'
import {
  getPurchaseOrderDetail,
  getInnerOrderDetail,
  getSalesOrderDetail
} from '@/api/indentManage/indent'
import InvoiceForm from '@/views/financialManage/invoiceManage/modules/invoiceForm'
const router = useRouter()
const route = useRoute()
const props = defineProps({
  // 查询参数
  tableParam: {
    type: Object,
    required: true,
    default: () => {
      return {
        id: '',
        type: '', //customer客户 order订单 project项目
        orderType: 'ord_order' //ord_order销售订单  ord_purchase_order采购订单 ord_inner_order内部订单
      }
    }
  }
  /* customerId: {
    type: [Number, String],
    require: false
  },
  orderId: {
    type: [Number, String],
    require: false
  } */
})
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const { invoice_manage_type } = proxy.useDict(
  'invoice_manage_type' //发票类型
)
const data = reactive({
  loading: false,
  tableList: [],
  countCrudData: { invoicedPrice: '', unInvoicePrice: '' },

  ids: [],
  selectArr: [],
  total: 0,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: undefined,
    customerId: undefined,
    projectId: undefined
  },
  params: {},
  dialogOpton: {
    open: false,
    title: '添加发票'
  },
  invoiceData: {}
})
let {
  loading,
  tableList,
  countCrudData,
  ids,
  selectArr,
  total,
  queryParams,
  params,
  dialogOpton,
  invoiceData
} = toRefs(data)

watchEffect(() => {
  if (props.tableParam) {
    switch (props.tableParam.type) {
      case 'order':
        queryParams.value.orderId = props.tableParam.id
        if (props.tableParam.orderType == 'ord_order') {
          getSalesOrderDetail(props.tableParam.id).then(async res => {
            let resData = res.data
            params.value.customerType = resData.customerType
              ? resData.customerType
              : undefined
            params.value.orderTitle = resData.customerType
              ? resData.title
              : undefined
            params.value.orderId = queryParams.value.orderId
            params.value.customerId = resData.customerId
              ? resData.customerId
              : undefined
            params.value.customerName = resData.customerName
              ? resData.customerName
              : undefined
            params.value.productList = resData.productList
          })
        } else if (props.tableParam.orderType == 'ord_purchase_order') {
          getPurchaseOrderDetail(props.tableParam.id).then(async res => {
            let resData = res.data
            params.value.customerType = resData.customerType
              ? resData.customerType
              : undefined
            params.value.orderTitle = resData.customerType
              ? resData.title
              : undefined
            params.value.orderId = queryParams.value.orderId
            params.value.customerId = resData.customerId
              ? resData.customerId
              : undefined
            params.value.customerName = resData.customerName
              ? resData.customerName
              : undefined
          })
        } else if (props.tableParam.orderType == 'ord_inner_order') {
          getInnerOrderDetail(props.tableParam.id).then(async res => {
            let resData = res.data
            params.value.customerType = resData.customerType
              ? resData.customerType
              : undefined
            params.value.orderTitle = resData.customerType
              ? resData.title
              : undefined
            params.value.orderId = queryParams.value.orderId
            params.value.customerId = resData.customerId
              ? resData.customerId
              : undefined
            params.value.customerName = resData.customerName
              ? resData.customerName
              : undefined
          })
        }
        break
      case 'customer':
        queryParams.value.customerId = props.tableParam.id
        getCustomerEditInfo(queryParams.value.customerId).then(async res => {
          let resData = res.data
          if (resData.bizCustomerAddDto.customerName) {
            params.value = {
              customerId: queryParams.value.customerId,
              customerName: resData.bizCustomerAddDto.customerName
            }
          }
        })
        break
      case 'project':
        queryParams.value.projectId = props.tableParam.id
        break
    }
    getList()
  }
  /* if (props.customerId && !props.orderId) {
    queryParams.value.customerId = props.customerId
    getList()
  } */
})
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
}
// 获取数据列表
function getList() {
  loading.value = true

  listInvoice(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })

  if (queryParams.value.orderId) {
    getCount()
  }
  console.log('获取数据')
}
// 获取统计数据
function getCount() {
  let params = {
    orderId: queryParams.value.orderId,
    orderType: props.tableParam.orderType
      ? props.tableParam.orderType
      : 'ord_order'
  }
  getInvoiceCount(params).then(res => {
    console.log('统计数据==》', res.data)
    countCrudData.value = res.data
  })
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}

function handleAdd() {
  // goTo('/financial/invoiceForm', { invoiceData: JSON.stringify(params.value) })
  dialogOpton.value.open = true
  dialogOpton.value.title = '添加发票'
  invoiceData.value = params.value
}
function handleExport() {
  let param = { ...queryParams.value }
  console.log('导出==》', param)
  proxy.downLoadByUrl(
    '/ord/ordinvoice/export',
    param,
    `发票记录_${new Date().getTime()}.xlsx`
  )
}
function handleDetails(row) {
  goTo('/financial/invoiceDetails', { invoiceId: row.id })
  // dialogOpton.value.open = true
  // dialogOpton.value.title = '添加发票'
  // invoiceData.value = { id: row.id }
}
function handleDelete(row) {
  let rowIds = row.id
  proxy.$modal
    .confirm('是否确认删除')
    .then(function () {
      let data = {
        ids: [rowIds],
        type: 'invoice'
      }
      return delInvoice(data)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
// 下载发票
const downLoadFile = url => {
  window.open(url)
}

function handleStopSubmit() {
  if (dialogOpton.value.title == '添加发票') {
    proxy.$refs.invoiceForm.handleSubmit().then(e => {
      if (e.code !== 200) return
      proxy.$modal.msgSuccess('保存成功')
      dialogOpton.value.open = false
    })
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: 600;
}
</style>
